package chapter07

/**
 *
 * @author cdhuangchao3
 * @date 2023/6/11 2:15 PM
 */
object Test17_CommonWordCount {
  def main(args: Array[String]): Unit = {
    val stringList = List(
      "hello",
      "hello world",
      "hello scala",
      "hello spark from scala",
      "hello flink from scala"
    )

    // 1. 对字符串进行切分，得到一个打散所有单词的列表
//    val wordList1 = stringList.map(_.split(" "))
//    val wordList2 = wordList1.flatten
//    println(wordList2)
    val wordList = stringList.flatMap(_.split(" "))

    // 2.相同的单词进行分组
    val groupMap = wordList.groupBy(a => a)
    println(groupMap)

    // 3.对分组的list取长度，得到每个单词个数
    val countMap = groupMap.map(kv => (kv._1, kv._2.length))
    println(countMap)

    // 4.将map转list，并排序取前三
    val wordCount = countMap.toList.sortWith(_._2 > _._2).take(3)
    println(wordCount)
  }
}
